<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Model\Customer;
use App\Model\Route;
use App\Text\Ucpaas;
class KehuController extends Controller
{
	// 调用客户导航栏页面
    public function index()
    {
    	return view('kehu.index');
    }
    // 调用客户列表页面
    public function kehulist()
    {
        if(session('wechat.role')){
            foreach(session('wechat.role') as $vo){
                if($vo=="总经理"){
                    $customer=Customer::all();
                }elseif($vo=="经理"){
                    $bumen=session('wechat.userid');
                    $bumen=\DB::table('admin_user_permissions')->where('user_id',$bumen)->first()->permission_id;
                    $bumen=\DB::table('admin_user_permissions')->where('permission_id',$bumen)->pluck('user_id');
                    $customer=Customer::whereIn('customer_weihu',$bumen)->get();
                }else{
                    $id=session('wechat.userid');
                    $customer=Customer::where('customer_weihu',$id)->get();
                }
            }
            foreach($customer as $k=>$vo){
                $result=\DB::table("crm_shengri")->where("leibie","客户")->where("customer_id",$vo->id)->where('date',date("Y"))->get();
                if($result->first()){
                    $customer[$k]['tixing']="已发送";
                }else{
                    $customer[$k]['tixing']="未发送";
                }
            }
            $shuliang=10;
            $customer=$customer->take($shuliang);
            $duanxin=\DB::table('crm_duanxin')->get();
            return view('kehu.kehulist',['customer'=>$customer,'duanxin'=>$duanxin,'shuliang'=>$shuliang]);
        }else{
            return redirect(url('/'));
        }
    }
    // 执行客户筛选查询功能
    public function kehusousuo(Request $request)
    {
        $list=json_decode($request['data']);
        if(session('wechat.role')){
            foreach(session('wechat.role') as $vo){
                if($vo=="总经理"){
                    $order=Customer::all();
                }elseif($vo=="经理"){
                    $bumen=session('wechat.userid');
                    $bumen=\DB::table('admin_user_permissions')->where('user_id',$bumen)->first()->permission_id;
                    $bumen=\DB::table('admin_user_permissions')->where('permission_id',$bumen)->pluck('user_id');
                    $order=Customer::whereIn('customer_weihu',$bumen)->get();
                }else{
                    $order=Customer::where('customer_weihu',session('wechat.userid'))->get();
                }
            }
            if($list->customer_type){
                $order=$order->where('customer_type',$list->customer_type);
            }
            if($list->customer_laiyuan){
                $laiyuan=['1'=>'网站','2'=>'转介绍','3'=>'上门','4'=>'电话销售','5'=>'老客户','6'=>'其他'];
                $laiyuan=array_search($list->customer_laiyuan,$laiyuan); 
                $order=$order->where('customer_laiyuan',$laiyuan);
            }
            if($list->customer_name){
                $ids=\DB::table("crm_customer")->where("customer_name","like","%".$list->customer_name."%")->pluck('id');
                $order=$order->whereIn('id',$ids);
            }
            if($list->customer_phone){
                $ids=\DB::table("crm_customer")->where("customer_phone","like","%".$list->customer_phone."%")->pluck('id');
                $order=$order->whereIn('id',$ids);
            }
            if($list->customer_danwei){
                $ids=\DB::table("crm_customer")->where("customer_danwei","like","%".$list->customer_danwei."%")->pluck('id');
                $order=$order->whereIn('id',$ids);
            }
            if($list->yuangong){
                 $ids=\DB::table("crm_customer")->where("yuangong","like","%".$list->yuangong."%")->pluck('id');
                $order=$order->whereIn('id',$ids);
            }
            foreach($order as $k=>$vo){
                $result=\DB::table("crm_shengri")->where("leibie","客户")->where("customer_id",$vo->id)->where('date',date("Y"))->get();
                if($result->first()){
                    $order[$k]['tixing']="已发送";
                }else{
                    $order[$k]['tixing']="未发送";
                }
            }
            $order=$order->take($list->shuliang);
            $dd['order']=$order;
            $dd['shuliang']=$list->shuliang;
            return json_encode($dd);
        }else{
            return json_encode('false');
        }
    }
    // 执行客户列表的短信发送功能
    public function customerduanxin(Request $request)
    {
        $list=json_decode($request['data']);
        $tiaoshu=\DB::table('crm_tiaoshu')->first();
        if($tiaoshu->weiyong<1){
            return json_encode("yuebuzu");
        }else{
            $customerid = rtrim($list->{'listid'},',');
            $customerid = explode(",", $customerid);
            $aa=0;
            $bb=0;
            foreach($customerid as $value)
            {
               //初始化必填
                $options['accountsid']='5767597e7e40a51fa9550e55c0c73ded';
                $options['token']='6503c50569710c29ff186153ad46a058';
                //初始化 $options必填
                $ucpass =new Ucpaas($options);
                //开发者账号信息查询默认为json或xml
                header("Content-Type:text/html;charset=utf-8");
                //短信验证码（模板短信）,默认以65个汉字（同65个英文）为一条（可容纳字数受您应用名称占用字符影响），超过长度短信平台将会自动分割为多条发送。分割后的多条短信将按照具体占用条数计费。
                $appId = "28578306399b4340af76010a6eb12ced";
                // $list=$request->except("_token");
                $customer=\DB::table("crm_customer")->where('id',$value)->first();
                $to="".$customer->customer_phone."";
                $templateId = "184303";
                $param="[".$customer->customer_name."]:".\DB::table("crm_duanxin")->where('id',$list->{'moban'})->first()->content."";
                $res=json_decode($ucpass->templateSMS($appId,$to,$templateId,$param));
                if($res->{'resp'}->{'respCode'}==000000){
                    $aa+=1;
                    $tiaoshu=\DB::table('crm_tiaoshu')->first();
                    \DB::table('crm_tiaoshu')->where('id', 1)->update(['syong' => $tiaoshu->syong+1,'weiyong'=>$tiaoshu->weiyong-1]);
                }else{
                    $bb+=1;
                } 
            }
            $huifu['chenggong']=$aa;
            $huifu['shibai']=$bb;
            return json_encode($huifu);
        }
    }
    // 调用客户编辑的客户信息
    public function kehubianji(Request $request)
    {
        $list=json_decode($request['data']);
        $customer_id=rtrim($list->{'listid'},',');
        $customer=Customer::find($customer_id);
        $laiyuan=['1'=>'网站','2'=>'转介绍','3'=>'上门','4'=>'电话销售','5'=>'老客户','6'=>'其他'];
        $customer->customer_laiyuan=$laiyuan[$customer->customer_laiyuan];
        return json_encode($customer);
    }
    // 进行客户信息编辑
    public function customerbianji(Request $request)
    {
        $list=json_decode($request['data']);
        $data=[];
        $laiyuan=['1'=>'网站','2'=>'转介绍','3'=>'上门','4'=>'电话销售','5'=>'老客户','6'=>'其他'];
        $laiyuan=array_keys($laiyuan,$list->{'customer_laiyuan'});
        $data['customer_laiyuan']=$laiyuan[0];
        $data['customer_name']=$list->{'customer_name'};
        $data['customer_sex']=$list->{'customer_sex'};
        $data['customer_danwei']=$list->{'customer_danwei'};
        $data['customer_phone']=$list->{'customer_phone'};
        $data['customer_weixin']=$list->{'customer_weixin'};
        $data['customer_qq']=$list->{'customer_qq'};
        $data['customer_email']=$list->{'customer_email'};
        $data['customer_sfz']=$list->{'customer_sfz'};
        if($list->{'customer_sfz'}!=''){
            $data['customer_shengri']=substr($list->{'customer_sfz'},-8,4);
        }
        $data['customer_beizhu']=$list->{'customer_beizhu'};
        $data['customer_age']=$list->{'customer_age'};
        $data['customer_type']=$list->{'customer_type'};
        if($data['customer_phone'] !=''){
            if(Customer::find($list->{'id'})->customer_phone==$data['customer_phone']){
                $aaa=Customer::updateOrCreate(array('id' => $list->{'id'}), $data);
            }else{
                $phone=Customer::where('customer_phone',$data['customer_phone'])->first();
                if($phone){
                    return json_encode('phone');
                }else{
                    $aaa=Customer::updateOrCreate(array('id' => $list->{'id'}), $data);
                }
            }
        }else{
            $aaa=Customer::updateOrCreate(array('id' => $list->{'id'}), $data);
        }
        if($aaa){
            return json_encode($aaa);
        }else{
            return json_encode('false');
        }
    }
    // 调用客户关怀的客户信息
    public function kehuguanhuai()
    {
        if(session('wechat.role')){
            foreach(session('wechat.role') as $vo){
                $customer=\DB::table("crm_shengri")->where("leibie","客户")->where('date',date("Y"))->pluck('customer_id');
                \DB::table('crm_customer')->where('customer_shengri','!=',date('md'))->where('customer_srxinxi',2)->update(['customer_srxinxi' => 1]);
                if($vo=="总经理"){
                    $customer=Customer::where('customer_shengri',date('md'))->whereNotIn('id', $customer)->where('customer_phone','!=','')->get();
                }elseif($vo=="经理"){
                    $bumen=session('wechat.userid');
                    $bumen=\DB::table('admin_user_permissions')->where('user_id',$bumen)->first()->permission_id;
                    $bumen=\DB::table('admin_user_permissions')->where('permission_id',$bumen)->pluck('user_id');
                    $customer=Customer::whereIn('customer_weihu',$bumen)->where('customer_shengri',date('md'))->where('customer_phone','!=','')->whereNotIn('id', $customer)->get();
                }else{
                    $id=session('wechat.userid');
                    $customer=Customer::where('customer_weihu',$id)->where('customer_shengri',date('md'))->where('customer_phone','!=','')->whereNotIn('id', $customer)->get();
                }
            }
            return view('kehu.kehuguanhuai',['customer'=>$customer]);
        }else{
            return redirect(url('/'));
        }
    }
    // 客户生日短信发送
    public function kehushengri()
    {
        $id=$_GET['id'];
        $tiaoshu=\DB::table('crm_tiaoshu')->first();
        if($tiaoshu->weiyong<1){
            return json_encode("yuebuzu");
        }else{
            //初始化必填
            $options['accountsid']='5767597e7e40a51fa9550e55c0c73ded';
            $options['token']='6503c50569710c29ff186153ad46a058';
            //初始化 $options必填
            $ucpass =new Ucpaas($options);
            //开发者账号信息查询默认为json或xml
            header("Content-Type:text/html;charset=utf-8");
            //短信验证码（模板短信）,默认以65个汉字（同65个英文）为一条（可容纳字数受您应用名称占用字符影响），超过长度短信平台将会自动分割为多条发送。分割后的多条短信将按照具体占用条数计费。
            $appId = "28578306399b4340af76010a6eb12ced";
            $to = "".Customer::find($id)->customer_phone."";
            $templateId = "184295";
            $param="".Customer::find($id)->customer_name."";
            $res=json_decode($ucpass->templateSMS($appId,$to,$templateId,$param));
            
            if($res->{'resp'}->{'respCode'}==000000){
                $tiaoshu=\DB::table('crm_tiaoshu')->first();
                \DB::table('crm_tiaoshu')->where('id', 1)->update(['syong' => $tiaoshu->syong+1,'weiyong'=>$tiaoshu->weiyong-1]);
                \DB::table("crm_shengri")->insert(
                  ['customer_id' => $id, 'date' => date("Y"),'leibie'=>'客户']
                );
                
                return json_encode("success");
            }elseif($res->{'resp'}->{'respCode'}==105147){
                return json_encode("pinfan");
            }else{
                return json_encode("shibai");
            }
        }
    }
    // 获取游客列表的游客信息
    public function youkelist()
    {
        if(session('wechat.role')){
            foreach(session('wechat.role') as $vo){
                if($vo=="总经理"){
                    $tourist=\DB::table("crm_tourist")->get();
                }elseif($vo=="经理"){
                    $bumen=session('wechat.userid');
                    $bumen=\DB::table('admin_user_permissions')->where('user_id',$bumen)->first()->permission_id;
                    $bumen=\DB::table('admin_user_permissions')->where('permission_id',$bumen)->pluck('user_id');
                    $aas=\DB::table('deal_tourist')->whereIn('user_id',$bumen)->pluck('tourist_id');
                    $tourist=\DB::table("crm_tourist")->whereIn('id', $aas)->get();
                }else{
                    $id=session('wechat.userid');
                    $aas=\DB::table('deal_tourist')->where('user_id',$id)->pluck('tourist_id');
                    $tourist=\DB::table("crm_tourist")->whereIn('id', $aas)->get();
                }
            }
            foreach($tourist as $k=>$vo){
                $result=\DB::table("crm_shengri")->where("leibie","游客")->where("customer_id",$vo->id)->where('date',date("Y"))->get();
                if($result->first()){
                    $vo->tixing="已发送";
                }else{
                    $vo->tixing="未发送";
                }
            }
            $shuliang=10;
            $tourist=$tourist->take($shuliang);
            $duanxin=\DB::table('crm_duanxin')->get();
            return view('kehu.youkelist',['tourist'=>$tourist,'shuliang'=>$shuliang,'duanxin'=>$duanxin]);
        }else{
            return redirect(url('/'));
        }
    }
    // 执行游客筛选查询功能
    public function youkesousuo(Request $request)
    {
        $list=json_decode($request['data']);
        if(session('wechat.role')){
            foreach(session('wechat.role') as $vo){
                if($vo=="总经理"){
                    $tourist=\DB::table("crm_tourist")->get();
                }elseif($vo=="经理"){
                    $bumen=session('wechat.userid');
                    $bumen=\DB::table('admin_user_permissions')->where('user_id',$bumen)->first()->permission_id;
                    $bumen=\DB::table('admin_user_permissions')->where('permission_id',$bumen)->pluck('user_id');
                    $aas=\DB::table('deal_tourist')->whereIn('user_id',$bumen)->pluck('tourist_id');
                    $tourist=\DB::table("crm_tourist")->whereIn('id', $aas)->get();
                }else{
                    $id=session('wechat.userid');
                    $aas=\DB::table('deal_tourist')->where('user_id',$id)->pluck('tourist_id');
                    $tourist=\DB::table("crm_tourist")->whereIn('id', $aas)->get();
                }
            }
            if($list->tourist_type){
                $tourist=$tourist->where('tourist_type',$list->tourist_type);
            }
            if($list->tourist_typename){
                $ids=\DB::table("crm_tourist")->where("tourist_typename","like","%".$list->tourist_typename."%")->pluck("id");
                $tourist=$tourist->whereIn('id',$ids);
            }
            if($list->tourist_name){
                $ids=\DB::table("crm_tourist")->where("tourist_name","like","%".$list->tourist_name."%")->pluck("id");
                $tourist=$tourist->whereIn('id',$ids);
            }
            if($list->tourist_phone){
                $ids=\DB::table("crm_tourist")->where("tourist_phone","like","%".$list->tourist_phone."%")->pluck("id");
                $tourist=$tourist->whereIn('id',$ids);
            }
            foreach($tourist as $k=>$vo){
                $result=\DB::table("crm_shengri")->where("leibie","游客")->where("customer_id",$vo->id)->where('date',date("Y"))->get();
                if($result->first()){
                    $vo->tixing="已发送";
                }else{
                    $vo->tixing="未发送";
                }
            }
            $tourist=$tourist->take($list->shuliang);
            $dd['tourist']=$tourist;
            $dd['shuliang']=$list->shuliang;
            return json_encode($dd);
        }else{
            return json_encode('false');
        }
    }
    // 执行游客列表的短信发送功能
    public function youkeduanxin(Request $request)
    {
        $list=json_decode($request['data']);
        $tiaoshu=\DB::table('crm_tiaoshu')->first();
        if($tiaoshu->weiyong<1){
            return json_encode("yuebuzu");
        }else{
            $customerid = rtrim($list->{'listid'},',');
            $customerid = explode(",", $customerid);
            $aa=0;
            $bb=0;
            foreach($customerid as $value)
            {
               //初始化必填
                $options['accountsid']='5767597e7e40a51fa9550e55c0c73ded';
                $options['token']='6503c50569710c29ff186153ad46a058';
                //初始化 $options必填
                $ucpass =new Ucpaas($options);
                //开发者账号信息查询默认为json或xml
                header("Content-Type:text/html;charset=utf-8");
                //短信验证码（模板短信）,默认以65个汉字（同65个英文）为一条（可容纳字数受您应用名称占用字符影响），超过长度短信平台将会自动分割为多条发送。分割后的多条短信将按照具体占用条数计费。
                $appId = "28578306399b4340af76010a6eb12ced";
                // $list=$request->except("_token");
                $customer=\DB::table("crm_tourist")->where('id',$value)->first();
                $to="".$customer->tourist_phone."";
                $templateId = "184303";
                $param="[".$customer->customer_name."]:".\DB::table("crm_duanxin")->where('id',$list->{'moban'})->first()->content."";
                $res=json_decode($ucpass->templateSMS($appId,$to,$templateId,$param));
                if($res->{'resp'}->{'respCode'}==000000){
                    $aa+=1;
                    $tiaoshu=\DB::table('crm_tiaoshu')->first();
                    \DB::table('crm_tiaoshu')->where('id', 1)->update(['syong' => $tiaoshu->syong+1,'weiyong'=>$tiaoshu->weiyong-1]);
                }else{
                    $bb+=1;
                } 
            }
            $huifu['chenggong']=$aa;
            $huifu['shibai']=$bb;
            return json_encode($huifu);
        }
    }
    // 调用游客关怀页面游客信息
    public function youkeguanhuai()
    {
        if(session('wechat.role')){
            foreach(session('wechat.role') as $vo){
                 $customer=\DB::table("crm_shengri")->where("leibie","游客")->where('date',date("Y"))->pluck('customer_id');
                \DB::table('crm_tourist')->where('tourist_shengri','!=',date('md'))->where('tourist_xinxi',2)->update(['tourist_xinxi' => 1]);
                if($vo=="总经理"){
                    $customer=\DB::table('crm_tourist')->where('tourist_shengri',date('md'))->whereNotIn('id', $customer)->where('tourist_phone','!=','')->get();
                }elseif($vo=="经理"){
                    $bumen=session('wechat.userid');
                    $bumen=\DB::table('admin_user_permissions')->where('user_id',$bumen)->first()->permission_id;
                    $bumen=\DB::table('admin_user_permissions')->where('permission_id',$bumen)->pluck('user_id');
                    $aas=\DB::table('deal_tourist')->whereIn('user_id',$bumen)->pluck('tourist_id');
                    $customer=\DB::table('crm_tourist')->whereIn('id',$aas)->where('tourist_shengri',date('md'))->whereNotIn('id', $customer)->where('tourist_phone','!=','')->get();
                }else{
                    $id=session('wechat.userid');
                    $aas=\DB::table('deal_tourist')->where('user_id',$id)->pluck('tourist_id');
                    $customer=\DB::table('crm_tourist')->whereIn('id',$aas)->where('tourist_shengri',date('md'))->whereNotIn('id', $customer)->where('tourist_phone','!=','')->get();
                }
            }
            return view('kehu.youkeguanhuai',['customer'=>$customer]);
        }else{
            return redirect(url('/'));
        }
    }
    // 游客生日短信发送
    public function youkeshengri()
    {
        $id=$_GET['id'];
        $tiaoshu=\DB::table('crm_tiaoshu')->first();
        if($tiaoshu->weiyong<1){
            return json_encode("yuebuzu");
        }else{
            //初始化必填
            $options['accountsid']='5767597e7e40a51fa9550e55c0c73ded';
            $options['token']='6503c50569710c29ff186153ad46a058';
            //初始化 $options必填
            $ucpass =new Ucpaas($options);
            //开发者账号信息查询默认为json或xml
            header("Content-Type:text/html;charset=utf-8");
            //短信验证码（模板短信）,默认以65个汉字（同65个英文）为一条（可容纳字数受您应用名称占用字符影响），超过长度短信平台将会自动分割为多条发送。分割后的多条短信将按照具体占用条数计费。
            $appId = "28578306399b4340af76010a6eb12ced";
            $to = "".\DB::table("crm_tourist")->where("id",$id)->first()->tourist_phone."";
            $templateId = "184295";
            $param="".\DB::table("crm_tourist")->where("id",$id)->first()->tourist_name."";
            $res=json_decode($ucpass->templateSMS($appId,$to,$templateId,$param));
            
            if($res->{'resp'}->{'respCode'}==000000){
                $tiaoshu=\DB::table('crm_tiaoshu')->first();
                \DB::table('crm_tiaoshu')->where('id', 1)->update(['syong' => $tiaoshu->syong+1,'weiyong'=>$tiaoshu->weiyong-1]);
                \DB::table("crm_shengri")->insert(
                  ['customer_id' => $id, 'date' => date("Y"),'leibie'=>'游客']
                );
                return json_encode("success");
            }elseif($res->{'resp'}->{'respCode'}==105147){
                return json_encode("pinfan");
            }else{
                return json_encode("shibai");
            }
        }
    }
    // 调用回访调查页面获取信息
    public function huifangdiaocha()
    {
        if(session('wechat.role')){
            foreach(session('wechat.role') as $vo){
                if($vo=="总经理"){
                    $diaocha=\DB::table("crm_diaocha")->get();
                }elseif($vo=="经理"){
                    $bumen=session('wechat.userid');
                    $bumen=\DB::table('admin_user_permissions')->where('user_id',$bumen)->first()->permission_id;
                    $bumen=\DB::table('admin_user_permissions')->where('permission_id',$bumen)->pluck('user_id');
                    $diaocha=\DB::table("crm_diaocha")->whereIn('yuangong', $bumen)->get();
                }else{
                    $id=session('wechat.userid');
                    $diaocha=\DB::table("crm_diaocha")->where('yuangong', $id)->get();
                }
            }
            $shuliang=10;
            $type=Route::where('parent_id',0)->get();
            $diaocha=$diaocha->take($shuliang);
            return view('kehu.huifangdiaocha',['diaocha'=>$diaocha,'type'=>$type,'shuliang'=>$shuliang]);
        }else{
            return redirect(url('/'));
        }
    }
    // 执行回访调查筛选查询功能
    public function huifangsousuo(Request $request)
    {
        $list=json_decode($request['data']);
        if(session('wechat.role')){
            foreach(session('wechat.role') as $vo){
                if($vo=="总经理"){
                    $diaocha=\DB::table("crm_diaocha")->get();
                }elseif($vo=="经理"){
                    $bumen=session('wechat.userid');
                    $bumen=\DB::table('admin_user_permissions')->where('user_id',$bumen)->first()->permission_id;
                    $bumen=\DB::table('admin_user_permissions')->where('permission_id',$bumen)->pluck('user_id');
                    $diaocha=\DB::table("crm_diaocha")->whereIn('yuangong', $bumen)->get();
                }else{
                    $id=session('wechat.userid');
                    $diaocha=\DB::table("crm_diaocha")->where('yuangong', $id)->get();
                }
            }
            if($list->customer_id){
                $ids=\DB::table("crm_diaocha")->where("customer_id","like","%".$list->customer_id."%")->pluck("id");
                $diaocha=$diaocha->whereIn('id',$ids);
            }
            if($list->date){
                $diaocha=$diaocha->where('date',$list->date);
            }
            if($list->type){
                $diaocha=$diaocha->where('type',$list->type);
            }
            if($list->didian){
                $diaocha=$diaocha->where('didian',$list->didian);
            }
            $diaocha=$diaocha->take($list->shuliang);
            $dd['diaocha']=$diaocha;
            $dd['shuliang']=$list->shuliang;
            return json_encode($dd);
        }else{
            return json_encode('false');
        }
    }
}
